import { ref, computed, nextTick, toRefs, reactive } from "vue";
import { useRouter } from "vue-router";
import { useKeepAlive, TAB_NAME_KEY } from "@/hook/index";
import { dataTypes } from "@/utils/index";
type InterfaceListMap = {
  [key: string]: any;
};
const routerListMap: InterfaceListMap = ref({});
/** 动态路由标签名称 */
const tabmenuName = ref<string>("");
// hook
export const useTabMenu = (params: any = {}) => {
  const { useDeleteComponent } = useKeepAlive();
  const router = useRouter();
  const state = reactive<any>({
    // 更多
    moreIndex: 0,
    // 更多路由
    more: false,
  });

  /**
   * 设置tabMenu名称
   */
  const setTabMenuName = (val: any) => {
    if (val?.meta && dataTypes().isObject(val?.meta)) {
      val.meta.title =
        tabmenuName.value || sessionStorage.getItem(TAB_NAME_KEY);
    }
    // 清空
    tabmenuName.value = "";
  };
  /**
   * 存储路由
   */
  const usePushRouter = (val: any = {}) => {
    const secondPath = getRouterSecond.value;
    // 不存在指定path，自动生成对应path的空数组
    if (!routerListMap.value[secondPath]) {
      routerListMap.value[secondPath] = [];
    }
    // 是否存在
    const isRouter = routerListMap.value[secondPath].filter(
      (item: any) => item.path === val.path
    );
    if (isRouter.length) {
      return;
    }
    // 写入
    val?.meta?.detailedTabmenu && routerListMap.value[secondPath].push(val);
    // meta元数据存在detailedTabmenu
    setTabMenuName(val);
    useShowScrollArrow();
  };

  /**
   * 删除路由
   */
  const useDeleteTabs = (path: any, subRouter: any) => {
    const secondPath = getRouterSecond.value;
    const routerList = routerListMap.value[secondPath];
    // 默认索引
    const index = routerListMap.value[secondPath].findIndex(
      (item: any) => item.path === path
    );

    if (index === -1) {
      return;
    }
    // 删除的路由路由是否最后一个
    const isLast = routerListMap.value[secondPath].length === 1;
    // 备份路由
    const backupRouter = routerListMap.value[secondPath][0];
    // 存储需要跳转的路由
    const next = isLast ? null : routerListMap.value[secondPath][index + 1];
    // 是否有子级的默认路由
    const subRouterItem = subRouter.length
      ? subRouter.filter(
          (item: any) => !item?.meta?.hidden && !item?.meta?.detailedTabmenu
        )
      : null;
    // 删除路由
    routerListMap.value[secondPath].splice(index, 1);
    useDeleteComponent(path);
    // 跳转的路由
    const toRouter =
      next ||
      (subRouterItem ? subRouterItem[subRouterItem.length - 1] : null) ||
      backupRouter.matched[1];
    // 是否当前路由
    if (path === currentRouter.value.path) {
      toPage(toRouter);
    }
    useShowScrollArrow();
  };

  /**
   * 路由跳转
   */
  const toPage = (item: any) => {
    router.push({
      path: item.path,
      query: item.query,
    });
  };

  /**
   * 返回路由
   */
  const useTabsRouters = computed(() => {
    const secondPath = getRouterSecond.value;
    return routerListMap.value?.[secondPath];
  });

  /**
   * 获取第二级路由
   */
  const getRouterSecond = computed(() => currentRouter.value.matched[1].path);

  /**
   * 当前路由
   */
  const currentRouter = computed(() => router.currentRoute.value);

  /**
   * 默认路由
   */
  const defaultRouter = () => {
    const rs = currentRouter.value.matched[1].children;
    const subRouter = rs.filter(
      (item) =>
        !item.meta ||
        (item.meta && !item?.meta?.hidden && !item?.meta?.detailedTabmenu)
    );
    return subRouter;
  };

  /** 动态路由tabMenu名称 */
  const useSetTabMenuName = (name: string) => {
    tabmenuName.value = name;
    sessionStorage.setItem(TAB_NAME_KEY, name);
  };

  const isShow = (meta: any) => {
    if (!meta) {
      return true;
    }
    // hidden属性为true，隐藏
    if (meta && meta?.hidden) {
      return false;
    }
    return true;
  };

  /**
   * 计滚动
   */
  const useShowScrollArrow = () => {
    nextTick(() => {
      let more = false;
      // 计算范围，是否显示箭头
      const tabsMenuContainer: HTMLElement = document.getElementById(
        params.id
      ) as HTMLElement;
      const maxWidth: number = tabsMenuContainer.offsetWidth;
      let tabsMenuItem: any = tabsMenuContainer.getElementsByTagName("li");
      const lis = [...tabsMenuItem];
      let width = 0;
      let index = 0;
      // 计算
      for (let i = 0; i < lis.length; i++) {
        const item = lis[i];
        const sum = width + item.offsetWidth + 8;
        width = sum;
        if (width > maxWidth) {
          index = i - defaultRouter().length;
          more = true;
          state.more = true;
          break;
        }
      }
      state.more = more;
      state.moreIndex = more ? index : 0;
    });
  };

  return {
    ...toRefs(state),
    isShow,
    usePushRouter,
    useDeleteTabs,
    useSetTabMenuName,
    useShowScrollArrow,
    useTabsRouters,
  };
};
